package net.pimpas.web.jsf.components.tree;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

import net.pimpas.util.reflection.ReflectionUtil;

public abstract class TreeNodeUtils {
	
	public static final void addNodeChild(TreeNode parent, TreeNode child, int position) {
		if(parent != null && child != null)
			parent.getChildren().add(position, child);
	}
	
	public static final void addNodeChild(TreeNode parent, TreeNode child) {
		addNodeChild(parent, child, parent.getChildren().size());
	}
	
	public static final void moveNode(TreeNode parent, TreeNode newParent, int childPosition, int newChildPosition) {
		if(parent == null || newParent == null || childPosition < 0 || parent.getChildren().size() < childPosition)
			return;
		
		TreeNode node = removeNode(parent, childPosition);
		newParent.getChildren().set(newChildPosition, node);
	}
	
	public static final void changeNodeParent(TreeNode node, TreeNode newParent) {
		if(node == null || newParent == null) return;
		
		if(node.getParent() != null)
			removeNode(node.getParent(), node);
		
		node.setParent(newParent);
	}
	
	public static final TreeNode removeNode(TreeNode parent, TreeNode child) {
		if(parent == null || child == null) return null;
		
		if(parent.getChildren().contains(child)) {
			parent.getChildren().remove(child);
			return child;
		}
		
		return null;
	}
	
	public static final TreeNode removeNode(TreeNode parent, int childPosition) {
		if(parent == null || childPosition < 0 || parent.getChildren().size() < childPosition) return null;
		
		return parent.getChildren().remove(childPosition);
	}
	
	public static final TreeNode createNode(Object ob, String labelP, String valueP, String iconOpened,
			String iconClosed, String iconLeaf) {
		TreeNode node = null;
		try {
			PropertyDescriptor propertyLabel = ReflectionUtil.getPropertyDescriptor(ob.getClass(), labelP);
			PropertyDescriptor propertyValue = ReflectionUtil.getPropertyDescriptor(ob.getClass(), valueP);
			String label = String.valueOf(propertyLabel.getReadMethod().invoke(ob));
			Object value = propertyValue.getReadMethod().invoke(ob);
			node = new TreeNode();
			node.setLabel(label);
			node.setValue(value);
			node.setIconOpened(iconOpened);
			node.setIconClosed(iconClosed);
			node.setIconLeaf(iconLeaf);
			node.setBean(ob);
		} catch (IllegalArgumentException e) {
		} catch (IllegalAccessException e) {
		} catch (InvocationTargetException e) {
		}
		
		return node;
	}
	
	public static final TreeNode createNode(Object ob, String labelP, String valueP) {
		return createNode(ob, labelP, valueP, null, null, null);
	}
	
	public static final void changeImageIcon(TreeNode node, String iconOpened, String iconClosed, String iconLeaf) {
		if(node != null) {
			node.setIconOpened(iconOpened);
			node.setIconClosed(iconClosed);
			node.setIconLeaf(iconLeaf);
		}
	}
}